var config = require('./config.js')
var mockData = require('./mock.js')
const { SERVER_URL } = require('./config.js');

module.exports = {
    fetchFilms: function(url, city, start, count, cb) {
        var that = this
        if (that.data.hasMore) {
            console.log('使用模拟数据')
            // 调试：打印数据条数
            let data
            if (url.includes('in_theaters')) {
                data = mockData.in_theaters
            } else if (url.includes('coming-soon')) {
                data = mockData.coming_soon
            } else if (url.includes('top250')) {
                data = mockData.top250
            }
            let allSubjects = data.subjects || [];
            let pageSubjects = allSubjects.slice(that.data.start, that.data.start + count);
            setTimeout(() => {
                if(pageSubjects.length === 0){
                    that.setData({
                        hasMore: false,
                        showLoading: false
                    })
                }else{
                    that.setData({
                        films: that.data.films.concat(pageSubjects),
                        start: that.data.start + pageSubjects.length,
                        showLoading: false
                    })
                }
                typeof cb == 'function' && cb({subjects: pageSubjects})
            }, 500)
        }
    },
    fetchFilmDetail: function(urlPath, id, cb, filmType) { // 增加 filmType 参数
        var that = this;
        const token = wx.getStorageSync('token');
        console.log('请求详情页时带的token:', token);
        console.log('请求详情header:', {
            'Authorization': 'Bearer ' + (token || '')
        });
        console.log('开始获取电影详情，ID:', id, '类型:', filmType);
        let requestUrl = `${SERVER_URL}/api/movies/${id}`;

        if (filmType === 'coming_soon') {
            requestUrl = `${SERVER_URL}/api/coming-soon/${id}`;
        }

        console.log('准备发送 wx.request 到 URL:', requestUrl);
        
        wx.request({
            url: requestUrl,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + (token || '')
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    const data = res.data;
                    if (data) {
                        wx.setNavigationBarTitle({
                            title: data.title
                        });
                        typeof cb.success == 'function' && cb.success(data);
                    } else {
                        console.error('后端返回空数据或未找到电影', id);
                        typeof cb.fail == 'function' && cb.fail(new Error('未找到电影'));
                    }
                } else {
                    console.error('获取电影详情失败，状态码:', res.statusCode, res.data);
                    typeof cb.fail == 'function' && cb.fail(new Error(res.data.message || '获取电影详情失败'));
                }
            },
            fail: (error) => {
                console.error('请求电影详情失败:', error);
                typeof cb.fail == 'function' && cb.fail(new Error('网络请求失败'));
            }
        });
    },
    fetchPersonDetail: function(url, id, cb) {
        var that = this;
        console.log('使用模拟数据获取人物详情')
        setTimeout(() => {
            const data = mockData.in_theaters.subjects[0].directors[0]
            that.setData({
                showLoading: false,
                personDetail: data
            })
            
            wx.setNavigationBarTitle({
                title: data.name
            })
            typeof cb == 'function' && cb(data)
        }, 500)
    },
    search: function(url, keyword, start, count, cb){
        var that = this;
        wx.request({
            url: `${SERVER_URL}/api/movies/search?keyword=${encodeURIComponent(keyword)}`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + (wx.getStorageSync('token') || '')
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    const data = res.data;
                    that.setData({
                        films: (that.data.films || []).concat(data),
                        start: that.data.start + data.length,
                        showLoading: false,
                        hasMore: data.length === count
                    });
                    wx.setNavigationBarTitle({
                        title: keyword
                    });
                    typeof cb == 'function' && cb(data);
                } else {
                    that.setData({ showLoading: false });
                }
            },
            fail: (error) => {
                that.setData({ showLoading: false });
            }
        });
    }
}